/*
@author: stanfor
@date: 2022/8/22 13:52
@Version: 1.0
@last modify time : 2022/8/22 13:52
*/

import React from 'react';
import { getAntdIcon } from '@U/tool';
import type { FormItemProps } from 'antd';

/** Pick 方法说明
 * @author: JasonStandFor
 * @description Desc:: 部分选择
 * @example
 interface User {
  id: number;
  name: string;
  age: number;
  gender: number;
  email: string;
}

 type PickUser = Pick<User, "id" | "name" | "gender">;
 // 等价于
 type PickUser = {
  id: number;
  name: string;
  gender: number;
};
 **/
export type Pick<T, K extends keyof T> = {
  [P in K]: T[P]
};

/** Exclude 方法说明
 * @author: JasonStandFor
 * @description Desc:: 属性排除
 * @example
 interface User {
    id: number;
    name: string;
    age: number;
    gender: number;
    email: string;
}

 type keys = keyof User; // -> "id" | "name" | "age" | "gender" | "email"

 type ExcludeUser = Exclude<keys, "age" | "email">;
 // 等价于
 type ExcludeUser = "id" | "name" | "gender";
 **/
export type Exclude<T, U> = (keyof T) extends U ? never : (keyof T);

/** Omit 方法说明
 * @author: JasonStandFor
 * @description Desc:: 属性排除
 * @example
 interface User {
    id: number;
    name: string;
    age: number;
    gender: number;
    email: string;
}

 // 表示忽略掉User接口中的age和email属性
 type OmitUser = Omit<User, "age" | "email">;
 // 等价于
 type OmitUser = {
  id: number;
  name: string;
  gender: number;
};
 **/
export type Omit<T, K extends keyof T> = Pick<T, Exclude<T, K>>;

export const getRulesConfig = (required: boolean, label: string, ruleIcon?: string|boolean, message?: string): Array<object> => {
  const defaultRules = [{
    required,
    message: message ?? `请输入${label}`,
  }];

  const withIconRules = [{
    required,
    validator: (rule: any, value: any) => {
      return new Promise((resolve: any, reject) => {
        if (!value) {
          return reject(
            <span>
              {getAntdIcon((typeof ruleIcon === 'string' && ruleIcon) || 'ExclamationCircleOutlined')}
              { message ?? `请输入${label}` }
            </span>
          );
        }
        resolve();
      });
    }
  }];
  try {
    if (typeof ruleIcon !== 'boolean' && typeof ruleIcon !== 'string' && ruleIcon !== undefined) {
      throw new Error('unexpected: ruleIcon 属性可能需要 String 或 Boolean 类型');
    }
    if (typeof ruleIcon === 'boolean' && ruleIcon && required) {
      return withIconRules;
    }
    if (typeof ruleIcon === 'string' && ruleIcon && required) {
      return withIconRules;
    }
    return defaultRules;
  } catch (err) {
    console.error(err);
  }
  return defaultRules;
};

export interface commonInterface {
  // 与表单绑定的 key
  name: string;
  // 表单 label
  label: string;
  // 栅格项
  span: string|number;
  // 必填项
  required: boolean;
  // 是否显示必填项的 icon, 为 String 类型时，只接受 @ant-design/icons 库的 icon
  ruleIcon: string|boolean;
  // Form.Item 属性配置
  formItemConfig: FormItemProps;
}
